import React from 'react'
import {connect} from 'react-redux'
import {messages} from "share/common";
import {Button, Form, Input, Select, Switch,message} from 'antd';
import CCGClassService from 'containers/setting/cost-center-group-class/cost-center-group-class.service';

const FormItem = Form.Item;

class EditCostCenterGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      sobList: [],//账套
      costCenterList: [],//账套对应的成本中心
      record: this.props.params.record,
    }
  }

  //获取数据
  componentWillMount() {
    this.getSetOfBooks();
    this.props.form.setFieldsValue(this.state.record)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.params.show !== this.props.params.show) {
      this.setState({
        record: nextProps.params.record,
        costCenterList:[]
      }, () => {
        if(nextProps.params.record.hasOwnProperty("description")){
          this.props.form.setFieldsValue(nextProps.params.record)
        }else{
          let item = Object.assign({description: ""}, nextProps.params.record)
          this.props.form.setFieldsValue(item)
        }
      });
    }
  }

  //获取账套列表
  getSetOfBooks = () => {
    CCGClassService.getSetOfBooks()
      .then(res => {
        this.setState({
          sobList: res.data,
        })
      })
  };
  //账套选择之后，请求成本中心
  setOfBooksIdChange = (sobId) => {
    this.props.form.setFieldsValue({'costCenterId': ''})
    let costCenterList = this.state.costCenterList;
    this.setState({
      costCenterList: []
    }, () => {
      this.getCostCenterListBySobId(sobId)
    })
  }
  //根据账套查询启用且未被关联的成本中心列表
  getCostCenterListBySobId = (sobId) => {
    let params = {
      setOfBooksId: sobId
    }
    CCGClassService.getCostCenterListBySobId(params)
      .then(res => {
        if(res.data && res.data.length && res.data.length>0){
          this.setState({
            costCenterList: res.data,
          })
        }else {
          message.warning(messages('setting.key1671')/*此账套下没有成本中心，请重新选择账套*/);
        }
      })
  }

  //点击确认
  handleSave = (e) => {
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = Object.assign(record, values);
        if (params.id) {
          this.updateCostCenterGroupClass(params);
        } else {
          this.createCostCenterGroupClass(params);
        }
      }
    })
  };

  //更新成本中心组类别
  updateCostCenterGroupClass = (params) => {
    this.setState({
      loading: true
    });
    CCGClassService.updateCostCenterGroupClass(params)
      .then(res => {
          this.setState({
            loading: false
          });
          this.props.close(true);
        }
      ).catch(err => {
      this.setState({
        loading: false,
      })
    })
  }
  //新增成本中心组类别
  createCostCenterGroupClass = (params) => {
    this.setState({
      loading: true
    });
    CCGClassService.createCostCenterGroupClass(params)
      .then(res => {
          this.setState({
            loading: false
          });
          this.props.close(true);
        }
      ).catch(err => {
      this.setState({
        loading: false,
      });
    })
  }
  //取消
  onCancel = () => {
    this.props.close();
  };
  //渲染账套与成本中心
  renderSob() {
    const {getFieldDecorator} = this.props.form;
    const {record, sobList, costCenterList} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    if (record.id) {
      return (
        <div>
          <FormItem {...formItemLayout}
                    label={messages('setting.key380')/*账套*/}>
            <Input disabled={true}
                   value={record.setOfBooksName}
                   placeholder={messages('common.please.input')}/>
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('setting.key903')/*成本中心*/}>
            <Input disabled={true}
                   value={record.costCenterName}
                   placeholder={messages('common.please.input')}/>
          </FormItem>
        </div>
      )
    } else {
      return (
        <div>
          <FormItem label={messages('setting.key380')/*账套*/}
                    {...formItemLayout}>
            {getFieldDecorator('setOfBooksId', {
              rules: [{
                required: true,
                message: messages('setting.key394')/*账套不能为空*/
              }]
            })
            (
              <Select
                placeholder={messages('common.please.select')/*请选择*/}
                onChange={this.setOfBooksIdChange}
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {sobList.map((option, index) => {
                  return <Option key={option.id}>{option.setOfBooksName}</Option>
                })}
              </Select>
            )
            }
          </FormItem>


          <FormItem label={messages('setting.key903')/*成本中心*/}
                    {...formItemLayout}>
            {getFieldDecorator('costCenterId', {
              rules: [{
                required: true,
                message: messages('setting.key1672')/*成本中心不能为空*/
              }]
            })
            (
              <Select
                placeholder={messages('common.please.select')/*请选择*/}
                disabled={costCenterList.length === 0}
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {costCenterList.map((option, index) => {
                  return <Option key={option.id}>{option.name}</Option>
                })}
              </Select>
            )
            }
            <span style={{color: 'gray'}}> {messages('setting.key1673')/*注：请先选择账套*/}
                  </span>
          </FormItem>
        </div>
      )
    }
  }
  render() {
    const {getFieldDecorator} = this.props.form;
    const {loading, record} = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    return (
      <div>
        <Form>
          <FormItem label={messages('common.column.status')/*状态*/}
                    {...formItemLayout}>
            {getFieldDecorator('enabled', {
              valuePropName: "checked",
            })
              (<Switch/>)
            }
          </FormItem>
          <FormItem label={messages('setting.key1668')/*成本中心组类别代码*/}
                    {...formItemLayout}>
            {getFieldDecorator('code', {
              rules: [{
                required: true,
                message: messages('setting.key1674')/*成本中心组类别代码不能为空*/
              }]
            })
              (<Input disabled={!!record.id}/>)
            }
            <span style={{color: 'gray'}}> {messages('setting.key1675')/*注：成本中心组类别代码保存后不可修改*/}
              </span>
          </FormItem>
          <FormItem label={messages('setting.key1665')/*成本中心组类别名称*/}
                    {...formItemLayout}>
            {getFieldDecorator('name', {
              rules: [{
                required: true,
                message: messages('setting.key1676')/*成本中心组类别名称不能为空*/
              }]
            })
              (<Input/>)
            }
          </FormItem>
          {this.renderSob()}
          <FormItem label={messages('setting.key1031')/*描述*/}
                    {...formItemLayout}>
            {getFieldDecorator('description', {})
              (<Input/>)
            }
          </FormItem>
          <div className="slide-footer">
            <Button type="primary"
                    onClick={this.handleSave}
                    loading={loading}>
              {messages('common.save')}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')}
            </Button>
          </div>
        </Form>
      </div>
    )
  }
}

EditCostCenterGroup.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {}
}

const wrappedEditCostCenterGroup = Form.create()(EditCostCenterGroup);
export default connect(mapStateToProps)(wrappedEditCostCenterGroup);
